﻿using Inovout.Cloud.DatabaseCluster.Models;
using Inovout.Cloud.DatabaseCluster.Service;
using Inovout.Cloud.DatabaseCluster.Web.Models;
using Inovout.Cloud.Web.Http;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;

namespace Inovout.Cloud.DatabaseCluster.Web.Controllers
{
    public class DatabaseController : CloudHttpController
    {
        private DatabaseService databaseService;
        public DatabaseController()
        {
            databaseService = (DatabaseService)ComponentRegistry.Resolve<IDatabaseService>();
        }

        static DatabaseController()
        {
            AutoMapper.Mapper.CreateMap<DatabaseInfo, Inovout.Cloud.DatabaseCluster.Models.Database>();
            AutoMapper.Mapper.CreateMap<Inovout.Cloud.DatabaseCluster.Models.Database, DatabaseInfo>();
        }

        [Route("v1/db")]
        public DatabaseInfo Post(Inovout.Cloud.DatabaseCluster.Models.Database database)
        {
            database.Project = base.Project;
            //Inovout.Cloud.DatabaseCluster.Models.Database database = BindToDomainModel(databaseInfo);
            databaseService.Save(database);
            return BindToViewModel(database);
        }

        [Route("v1/db/")]
        public object Get()
        {
            var result = new Dictionary<string, object>{
            {
                "items", 
                    ((IEnumerable<Database>)databaseService.FindAllByProject(base.Project)).Select(db => BindToViewModel(db))
            }
            };
            return result;
        }
        private DatabaseInfo BindToViewModel(Inovout.Cloud.DatabaseCluster.Models.Database domainDatabase)
        {
            DatabaseInfo database = AutoMapper.Mapper.Map<Inovout.Cloud.DatabaseCluster.Models.Database, DatabaseInfo>(domainDatabase);
            return database;

        }
        private Inovout.Cloud.DatabaseCluster.Models.Database BindToDomainModel(DatabaseInfo viewDatabase)
        {
            Inovout.Cloud.DatabaseCluster.Models.Database database = AutoMapper.Mapper.Map<DatabaseInfo, Inovout.Cloud.DatabaseCluster.Models.Database>(viewDatabase);
            database.Project = base.Project;
            return database;
        }
    }
}